<?php
    require('common.php');
        
    $db = new Database();
    $user = getUser($db);
    
    // Error check
    if($user['group'] < 2) {
        redirect('index.php');
        exit();
    }
    checkCsrfGuard();
    if(!isset($_POST['user']) || !isset($_POST['password']) || 
       !isset($_POST['realname']) || !isset($_POST['id']) || !isset($_POST['group']))
        throw new Exception('Bad request.');
    if($_POST['group'] != '1' && $_POST['group'] != '2')
        throw new Exception('Bad request.');

    // Check that the username isn't taken
    $result = $db->query('SELECT id FROM '.config('DB_PREFIX').'users '.
        'WHERE name='.$db->escape($_POST['user']).
        ' AND NOT id='.intval($_POST['id']));
    if(mysqli_num_rows($result) > 0) {
        message(LANG('USERNAME_TAKEN'), 
            'javascript: history.go(-1);',
            lang('BACK_TO_USERS'));
        exit();
    }
    
    // Update the user
    $db->query('UPDATE '.config('DB_PREFIX').'users SET '.
        'name='.$db->escape($_POST['user']).', '.
        'group_id='.intval($_POST['group']).', '.
        'real_name='.$db->escape($_POST['realname']).' '.
        'WHERE id='.intval($_POST['id']));
    
    // Update the password
    if($_POST['password'] != '') {
        $salt = generateSalt();
        $db->query('UPDATE '.config('DB_PREFIX').'users SET '.
            'password=\''.sha1($salt.$_POST['password']).'\', '.
            'salt=\''.$salt.'\' '.
            'WHERE id='.intval($_POST['id']));
    }
    
    // Success
    redirect('users.php');
?>